package main

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"log"
	"my_chat/dao/redis_m"
	"sync"
)

var wg sync.WaitGroup

func sub(ctx context.Context, rdb *redis.Client)  {
	pubsub := rdb.Subscribe(ctx, "mychannel1")

	// Wait for confirmation that subscription is created before publishing anything.
	_, err := pubsub.Receive(ctx)
	if err != nil {
		panic(err)}

		// Go channel which receives messages.
	ch := pubsub.Channel()

	// Consume messages.
	for msg := range ch {
		fmt.Println(msg.Channel, msg.Payload)
		if msg.Payload == "end"{
			_ = pubsub.Close()
			break
		}

	}
	print("sub end")
	wg.Done()
}

func pub(ctx context.Context, rdb *redis.Client)  {
	// Publish a message.
	for i:=0; i<10; i++{
		err := rdb.Publish(ctx, "mychannel1", "hello").Err()
		if err != nil {
			panic(err)
		}
	}

	err := rdb.Publish(ctx, "mychannel1", "end").Err()
	if err != nil {
		panic(err)
	}
	wg.Done()
	print("pub end")
}

func ValidationAuth()  {
	//获取
	ctx := context.Background()
	rets, err := redis_m.Client.HMGet(ctx, "hash_test", "name").Result()
	log.Println("rets:", rets, err)
}

func main() {
	a := "nam"
	datas := map[string]interface{}{
		a: "l",
	}

	//wg.Add(2)
	redis_m.Init()
	rdb := redis_m.Client
	ctx := context.Background()
	//go sub(ctx, rdb)
	//go pub(ctx, rdb)
	//wg.Wait()
	//fmt.Println("end")
	//添加
	if err := rdb.HMSet(ctx, "hash_test", datas).Err(); err != nil {
		fmt.Println(err)}

	// 获取
	rets, err := rdb.HMGet(ctx, "hash_test", "name").Result()
	if err!=nil{
		fmt.Println(err)
	}
	fmt.Println(rets)
	fmt.Println("p")
	}

